package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.PatientResponse;
import com.rest.response.RecordResponse;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;

/**
 * Created by Administrator on 2018/5/28.
 */

public class PatientDetailActivity extends BaseActivity {

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_detail)
    TextView tv_detail;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_diagnose)
    TextView tv_diagnose;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.tv_group)
    TextView tv_group;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    MyAdapter adapter;

    String id;
    String tbPatientId;
    List<RecordResponse.Record> list = new ArrayList<>();

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager( PatientDetailActivity.this );
        manager.setOrientation( LinearLayoutManager.VERTICAL );
        recyclerView.setLayoutManager( manager );
        adapter = new MyAdapter();
        recyclerView.setAdapter( adapter );
        recyclerView.addItemDecoration( new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw( c, parent, state );
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets( outRect, view, parent, state );
                outRect.bottom = DpUtil.dip2px( PatientDetailActivity.this, 1 );
            }
        } );
    }

    @Override
    protected void initData() {
        id = getIntent().getStringExtra( "id" );
        getPatientInfo( id );
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_patient_detail;
    }

    @OnClick(R.id.group)
    void group() {
        Bundle bundle = new Bundle();
        bundle.putString( "id", tbPatientId );
        startActivityForResult( GroupManageActivity.class, bundle, 1 );
    }

    @OnClick(R.id.btn_phone)
    void btn_phone() {
        RxPermissions rxPermissions = new RxPermissions( this );
        rxPermissions.request( Manifest.permission.CALL_PHONE )
                .subscribe( new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            Intent intent = new Intent( Intent.ACTION_CALL );
                            Uri data = Uri.parse( "tel:" + tv_phone.getText().toString() );
                            intent.setData( data );

                            if (ActivityCompat.checkSelfPermission( mContext, Manifest.permission.CALL_PHONE ) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            startActivity( intent );
                        } else {
                            //只有用户拒绝开启权限，且选了不再提示时，才会走这里，否则会一直请求开启
                            ToastUtil.showToast( mContext, "你禁止了拨打电话的权限" );
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                } );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                assert data != null;
                tv_group.setText( data.getStringExtra( "group" ) );
            }
        }
    }

    private void getPatientInfo(String id) {
        RestProxy.getInstance().getPatientInfo( id, new Observer<PatientResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PatientResponse patientResponse) {
                tv_name.setText( patientResponse.data.patientName );
                tv_phone.setText( patientResponse.data.phone );
                tv_address.setText( patientResponse.data.addr );
                tv_diagnose.setText( patientResponse.data.diagnoseName );
                tv_detail.setText( patientResponse.data.sex + " " + patientResponse.data.age );
                tv_time.setText( patientResponse.data.createTime );
                tv_group.setText( patientResponse.data.groupName );
                tbPatientId = patientResponse.data.tbPatientId;
                getRecord();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        } );
    }


    private void getRecord() {
        RestProxy.getInstance().getRecord( tbPatientId, new Observer<RecordResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RecordResponse recordResponse) {
                list.addAll( recordResponse.data.records );
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        } );
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public MyAdapter.Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            MyAdapter.Holder myHolder;
            myHolder = new MyAdapter.Holder( LayoutInflater.from( PatientDetailActivity.this ).inflate( R.layout.item_record, parent, false ) );
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NotNull MyAdapter.Holder holder, final int position) {
            if (position == 0) {
                holder.img.setImageResource( R.mipmap.shijian );
                holder.tv_type.setTextColor( getResources().getColor( R.color.mainGreen ) );
                holder.tv_time.setTextColor( getResources().getColor( R.color.mainGreen ) );
            } else {
                holder.img.setImageResource( R.mipmap.shijian1 );
                holder.tv_type.setTextColor( getResources().getColor( R.color.lightBlack ) );
                holder.tv_time.setTextColor( getResources().getColor( R.color.lightBlack ) );
            }
            holder.itemView.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString( "diagnoseId", list.get( position ).id );
                    startActivity( DiagnoseOrderDetailActivity.class, bundle );
                }
            } );
            holder.tv_type.setText( list.get( position ).diagType );
            holder.tv_time.setText( list.get( position ).createTime );
            holder.tv_main.setText( "主诊断:" + list.get( position ).diagnoseName );
            holder.tv_advice.setText( "医生意见:" + list.get( position ).diagnoseResult );
//            ImageLoaderHelper.getInstance().GlideImageLoader(DepartmentListActivity.this,doctorList.get(position).);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_type, tv_time, tv_main, tv_advice;
            ImageView img;

            public Holder(View itemView) {
                super( itemView );
                tv_type = itemView.findViewById( R.id.tv_type );
                tv_time = itemView.findViewById( R.id.tv_time );
                tv_main = itemView.findViewById( R.id.tv_main );
                tv_advice = itemView.findViewById( R.id.tv_advice );
                img = itemView.findViewById( R.id.img );
            }
        }
    }

}



